package com.smartrobot.smartrobot.activity;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.smartrobot.smartrobot.Common.Common;
import com.smartrobot.smartrobot.Common.CommonFunc;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.adapter.ChatListViewAdapter;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.pojo.getFriendListPojo;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.Message;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.util.check;
import com.smartrobot.smartrobot.websocket.socketUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

//import com.smartrobot.smartrobot.Common.Common;

/**
 * Created by Administrator on 2015/1/7.
 */
public class ChatActivity extends Activity{


    /*组件*/
    private ListView chatListView;
    private ImageView sendButton;
    private EditText editMsg;
    private TextView nickName;



    private ChatListViewAdapter adapter;
    private getFriendListPojo friendPojo;
    private List<Message> chatList,msgHistoryList;
    private Message message;
    public static List<Message>send_queue = new ArrayList<Message>();



    /*改变消息列表，type=0为添加，type=1为减少*/
    public static void  change_send_queue(Message message,int type){

        //保存信息到发送的消息列表中
        send_queue.add(message);

    }






    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.page_message_chating);

        init();
        getParam();


        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                String say = editMsg.getText().toString();
                if(!check.check_stringNotNull(say)){
                    return;
                }
                message.setSay(say);

                String Time = CommonFunc.getTime();
                Log.e("=======time=======",Time);
                message.setTime(Time);

                String sendStr = message.sendMsg("2", "text", say, getApplicationContext());
                Log.e("=====格式化后的输出====",sendStr );

                socketUtil.socket_send_2(sendStr, getApplicationContext());

                Message tempMessage = new Message();

                tempMessage = message.clone();

                change_send_queue(tempMessage,0);


                adapter.notifyChange(tempMessage,0);
            }
        });





    }


    void init(){
        if(friendPojo!=null)
            Log.e("=======friendPojo======",friendPojo.toString());
        initView();
    }

    void initView(){

        chatListView = (ListView)findViewById(R.id.chatting_listView);
        nickName = (TextView)findViewById(R.id.chatting_nickName);
        sendButton = (ImageView)findViewById(R.id.chatting_sending);
        editMsg = (EditText)findViewById(R.id.chatting_say);

        msgHistoryList = new ArrayList<Message>();
        adapter = new ChatListViewAdapter(getApplicationContext(),msgHistoryList);
        chatListView.setAdapter(adapter);



    }


    void getParam(){

        Bundle bundle = this.getIntent().getBundleExtra("data");
        switch (bundle.getInt("flag")){
            case 0:
                break;
            case 1:
                friendPojo = new getFriendListPojo();
                friendPojo  = (getFriendListPojo)bundle.getSerializable("user_msg");
                message = new Message(friendPojo.getUserId(),friendPojo.getHeadImg(),friendPojo.getName(),friendPojo.getUserAccount(),friendPojo.getReName(),"","");
                saveChatList(message);
                break;
            default:break;

        }

    }

    void saveChatList( final Message message){
        new Thread(new Runnable() {
            @Override
            public void run(){
                try{
                    chatList = new ArrayList<Message>();

                    String path = getApplicationContext().getFilesDir() + "/"+ CommonFunc.stringToMD5(User.getInstance().getId() + Common.chat_file);  //绝对路径
                    String abPath = CommonFunc.stringToMD5(User.getInstance().getId() + Common.chat_file); //相对路径

                    File charFile=new File(path);
                    if(!charFile.exists()){
                        chatList.add(message);
                        Log.d("=======文件不存在=====", path);
                        FileUtil.saveCircleMsgToFile(chatList, abPath, getApplicationContext());

                    }else{
                        chatList = ( List<Message>) FileUtil.ReadCircleMsgFromFile(abPath, getApplicationContext());

                        int listSize = chatList.size();

                        for(int i=0;i<listSize;i++){
                            Log.e("=====目前的位置====",i+"");
                            if(chatList.get(i).getId().equals(message.getId())){
                                break;
                            }
                            if(i==listSize-1){
                                chatList.add(message);
                            }
                        }

                        FileUtil.saveCircleMsgToFile(chatList, abPath, getApplicationContext());
                        Log.d("=======文件存在======", path);
                    }
                }catch (Exception e){
                    Log.e("===============diuleiluomu=======",e.toString());
                    LogToSd.log_init();
                    LogToSd.error("保存最近联系人失败");
                    LogToSd.error(e.toString());
                }

            }
        }).start();
    }


    @Override
    public void onRestart(){
        if(friendPojo!=null)
            Log.e("=======friendPojo======",friendPojo.getUserId());
        super.onRestart();
    }

}
